<template>
  <div class="write-secret-info">
    <group class="none-bottom-border">
      <cell-box class="cellbox-item">
        <flexbox class="select-images-list" style="flex-direction:column;">
          <flexbox-item class="title" style="margin-bottom:0;width:auto;" :span="12">
            附件
          </flexbox-item>
          <div class="value annex-block">
            <div class="annex-inner" v-for="(item,index) in fileList" :key="index">
              <a :href="item" class="annex-inner-title" target="_blank" >{{item.slice(item.indexOf("_")+1,item.length)}}</a>
              <div class="annex-inner-close">
                <i class="icon icon-contract" @click="removeFile(index)"></i>
                <!-- <img width="20" src="../../assets/images/delete_icon@3x.png" @click="removeFile(index)"> -->
              </div>
            </div>
            <flexbox class="select-images-list">
              <flexbox-item class="select-img" v-show="fileList.length < 9">
                <!-- <input type="file" @change="getFileUrl()" ref="inputDOM" multiple accept="image/*"> -->
                <input @change="getFileUrl($event)" ref="inputDOM" type="file" id="upload_file" multiple>
              </flexbox-item>
            </flexbox>
            <div class="notes" v-show="fileList.length < 9">可上传jpg/pdf/word格式</div>
          </div>
        </flexbox>
      </cell-box>
    </group>
  </div>
</template>

<script>
  import { Group, CellBox, Flexbox, FlexboxItem, XTextarea, Datetime } from 'vux';
  import { Queue } from '@/assets/js/classLibrary.js';
  import qs from 'qs';
  let config = {
        //添加请求头
        headers: { "Content-Type": "multipart/form-data" },
        //添加上传进度监听事件
        // onUploadProgress: e => {
        //   var completeProgress = ((e.loaded / e.total * 100) | 0) + "%";
        //   this.progress = completeProgress;
        // }
      };
  export default {
    name: 'AskLeaveInfo',
    data () {
      return {
        fileUploadList:[],
        uploadQueue: new Queue(), // 圖片上傳隊列
        previewerFileList:[], //显示上传文件
        size:'',
        fileList:[] //待储存到数据库的文件路径
      };
    },
    components: {
      Group,
      CellBox,
      Flexbox,
      FlexboxItem,
      XTextarea,
      Datetime
    },
    mounted () {
    },
    methods: {
      getFileUrl: function (e) {
        // input file element
        let inputEl = this.$refs.inputDOM;
        let filesArr = inputEl.files;
        let oldFileLength = this.fileList.length;
        let newFileLength = inputEl.files.length + oldFileLength;
        // 限制文件數量
        if (newFileLength > 9) {
          this.toastShow = true;
          this.toastText = '你只能上传9个文件';
          return false;
        }
        // 遍歷讀取文件
        for (let i = 0; i < filesArr.length; i++) {
          // 限制文件大小
          let size = filesArr[i].size / 1024;
          if (size > 10 * 1024) {
            this.toastShow = true;
            this.toastText = '单个文件不能超过10M';
            return false;
          }
          let reader = new FileReader();
          let _this = this;
          reader.onload = function () {
            let result = reader.result;
            let base64Header = result.slice(0, result.indexOf(',') + 1);
            let base64UploadUrl = result.replace(base64Header, '');
            if (!_this.isCorrectfile(base64Header)) {
              alert('只允許上傳jpg/pdf/word格式文件');
              return false;
            }
            _this.fileUploadList.push(filesArr[i]);
            _this.uploadQueue.enqueue(filesArr[i]);
            // 全部加入隊列后執行上傳
            if (i === filesArr.length - 1) {
              _this.uploadFile();
              _this.$parent.loadingShow = true;
              inputEl.value = '';
            }
          };
          reader.readAsDataURL(filesArr[i]);
        }
      },
      // 判断文件是否符合要求
      isCorrectfile: function (url) {
        if (url.indexOf('image') === -1 && url.indexOf('pdf') === -1 && url.indexOf('word') === -1) {
          return false
        };
        return true;
      },
      uploadFile: function () {
        this.$parent.loadingShow = true;
        if (!this.uploadQueue.empty()) {
          let file = this.uploadQueue.getFirst()
          // let postData = {
          //   data: {
          //     file: this.uploadQueue.getFirst()
          //   }
          // };
          let param = new FormData();
          param.append("name", file.name);
          param.append("file", file);
        // console.log(param.get("file"));
          // this.axios.post('/Process/FileUpdate', qs.stringify(postData))
          this.axios.post('/Process/FileUpdate', param, config)
          .then((res) => {
            this.$parent.loadingShow = false;
            if (res.data.IsScuess === 0) {
              this.fileList.push(...res.data.Filepath)
              // console.log(...res.data.Filepath)
              this.previewerFileList.push(file.name);
              this.uploadQueue.dequeue();
              this.uploadFile();
            } else {
              this.toastShow = true;
              this.toastText = `上传文件时发生错误，错误信息：${res.data.ExMessage}`;
              this.fileUploadList = [];
              this.uploadQueue.clear();
            }
          })
          .catch((err) => {
            this.$parent.loadingShow = false;
            this.toastShow = true;
            this.toastText = `上传文件时发生错误，错误信息：${err}`;
            this.fileUploadList = [];
            this.uploadQueue.clear();
          });
        } else {
          this.$parent.loadingShow = false;
        }
      },
      removeFile(index){
        this.fileList.splice(index,1)
        this.previewerFileList.splice(index,1)
      },
    }
  };
</script>

<style lang="scss" scoped>
  @import '../../assets/style/variable';
  .write-secret-info{
    .none-bottom-border{
      .annex-block{
        margin-left:16px;
        width: 100%;
        .annex-inner{
          display:flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: getRem(10);
          .annex-inner-title{
            width:80%;
            white-space:normal;
            overflow: auto;
          }
          .annex-inner-close{
            width:60px;
            text-align: right;
          }
        }
        .notes{
            display:block;
            margin-top:-12px;
            color:#ccc;
        }
      }
    }  
  }
  .cellbox-item{
    padding: 0 15px;
    &:before{
      border-color: #e6e6e6;
    }
    .title{
      color: #666;
      font-size: getRem(28);
      padding: getRem(32) 0;
    }
    .value{
      font-size: getRem(28);
    }
    .date-pciker{
      padding: getRem(32) 0;
      a{
        display: inline;
        padding: 0;
        color: #ddd;
        &:before{
          content: none;
        }
      }
      .has-value{
        color: #333;
      }
      .separation-symbol{
        color: #666;
      }
    }
    .leave-minute{
      input{
        display: block;
        width: calc(100% - 15px);
        border: 0; 
        padding: getRem(32) 0;
        line-height: getRem(38);
        font-size: getRem(28);
        &::placeholder{
          color: #ddd;
        }
      }
    }
    .apply-reason{
      padding: getRem(32) 0;
    }
    .leave-type{
      padding: getRem(32) 0;
      label{
        display: block;
        line-height: getRem(42);
        padding: 0 getRem(10) getRem(10) getRem(50);
        position: relative;
      }
      .other-type{
        display: inline-block;
        width: calc(100% - #{getRem(120)});
        border: 0;
        font-size: getRem(28);
        line-height: getRem(50);
        border-radius: 0;
        padding: 0 getRem(10);
        border-bottom: .5px solid #ddd;
        &:disabled{
          background: #fff;
        }
      }
      .apply-radio{
        position: absolute;
        left: 0;
        top: getRem(3);
        display: inline-block;
        appearance: none;
        -webkit-appearance: none;
        width: getRem(36);
        height: getRem(36);
        background: url(../../assets/images/radio-default.png) no-repeat center center;
        background-size: getRem(36) getRem(36);
        &:checked{
          background-image: url(../../assets/images/radio-selected.png);
        }
      }
    }
    .select-images-list{
      margin-top: getRem(20);
    }
  }
  .vux-flexbox{
    align-items: flex-start;
  }
  .icon-contract{
    background: url(../../assets/images/delete_icon@3x.png) no-repeat center;
    background-size: getRem(50) getRem(50);
  }
  .icon{
    display: block;
    height: getRem(80);
  }
  .vux-flexbox-item.title{
    padding: 16px 0px 8px 0px;
  }
  .vux-flexbox.select-images-list.vux-flex-row{
    margin: 0;
    padding: 0;
  }
  .value .vux-flexbox.select-images-list.vux-flex-row{
    padding: 0!important;
    margin: 0!important;
    margin-left: -17.536px!important;
    margin-bottom: 9px!important;
    margin-top: 8px!important;
  }
</style>